//
//  YRComposeController.swift
//  新浪微博
//
//  Created by Viper on 16/7/3.
//  Copyright © 2016年 Viper. All rights reserved.
//

import UIKit

class YRComposeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()

    }
    
    //MARK: - 设置视图
    private func setupUI(){
        
    view.backgroundColor = UIColor.whiteColor()
        
          setupNav()
        
        //添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeToolBar)
        composeTextView.addSubview(pictureView)
        //添加约束
        
        composeTextView.snp_makeConstraints { (make) in
            
           make.edges.equalTo(view).offset(UIEdgeInsetsZero)
            
        }
        composeToolBar.snp_makeConstraints { (make) in
            
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        pictureView.snp_makeConstraints { (make) in
            
            make.top.equalTo(composeTextView).offset(100)
            make.leading.trailing.equalTo(composeTextView).offset(10)
            make.width.height.equalTo(SCREENW - 20)
        }
        
        
        //弹出相册
        pictureView.composePircureViewClosure = { [weak self] ()->() in
            
            self?.selectImage()
            
        }
        
        
        //监听composeToolBar中的按钮点击
        
        composeToolBar.closure = {[weak self] (type : YRComposeToolBarType)->() in
          
            switch type {
            case .Picture:
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                self?.switchKeyboard()
            case .Add:
                print("加号")
            }
        }
        
        //通过系统通知监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YRComposeController.keyboardDidChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //表情键盘删除按钮通知
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YRComposeController.deleteBtnClick), name: EmotionDeledeNoti, object: nil)
        
        //表情键盘上表情按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YRComposeController.emotionButtonClick(_:)), name: EmotionButtonNoti, object: nil)
        
    }
    
    @objc private func emotionButtonClick(noti : NSNotification){
    
//        print("点击表情")
        
        //判断object是否为nil 而且能否转成emotion
        guard let emotion = noti.object as? YREmotion else{
        
            return
            
        }
        
        if emotion.isEmoji {
            //emoji表情
            composeTextView.insertText(((emotion.code ?? "") as NSString).emoji())
            
        }else{
            //记录composeTextView上一次的副文本记录
            let oldAttr = NSMutableAttributedString(attributedString:composeTextView.attributedText )
            
            //图片表情
            //设置image
         let path = emotion.path ?? ""
          let png = emotion.png ?? ""
            let name = path + png
            //文本附件->可以设置图片 (使用它需要设置bounds,显示图片有可能很大 保证图片文字一样高 还有位置)
          let att = YRTextAttachment()
            //设置emotion
            att.emotion = emotion
            att.image = UIImage(named: name, inBundle: YREmotionTools.sharedTools.emotionBundle, compatibleWithTraitCollection: nil)
            //设置bound
            let lineHeight = composeTextView.font!.lineHeight
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            //创建一个可变的副文本
            let attr = NSAttributedString(attachment: att)
            //拼接方式不可取
//            oldAttr.appendAttributedString(attr)
            //获取选中的光标
            let selectRange = composeTextView.selectedRange
            //插入方式不可取
//            oldAttr.insertAttributedString(attr, atIndex:selectRange.location)
            //替换方式
            oldAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            //设置副文本的font
            oldAttr.addAttributes([NSFontAttributeName:composeTextView.font!], range: NSRange(location: 0, length: oldAttr.length))
            composeTextView.attributedText  = oldAttr
            //更改composeTextView光标
            composeTextView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            //发送一个系统通知 隐藏或者显示textView中的文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            //调用代理方法使右侧按钮状态改变
            composeTextView.delegate?.textViewDidChange!(composeTextView)
            
        }
        
        
    }
    
   func deleteBtnClick(){
        
//        print("删除按钮事件")
        //相当于回退一个
        composeTextView.deleteBackward()
    }
    
    func keyboardDidChangeFrame(noti: NSNotification){
        
//        print(noti)
        //mac开发中是NSRect 移动端开发是CGRect 需要选转成NSValue 再转换成CGRect
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
//        print(rect.origin.y)
        //更新toolbar约束
        composeToolBar.snp_updateConstraints { (make) in
            
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(0.2) {
            //更新布局
            self.view.layoutIfNeeded()
        }
        
    }
    //移除通知
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    //MARK: - 导航栏信息
    private func setupNav(){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(YRComposeController.cancelClick))
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action:#selector(YRComposeController.sendClick))
        //右侧按钮不能点击
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        self.navigationItem.titleView = navLabel
        
        
    }
    
    //MARK: - 监听事件
   @objc private func cancelClick(){
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
   @objc private func sendClick(){
    
    
    
//    print(composeTextView.attributedText)
    /*
     闭包中的参数
     -01 得到遍历结果
     -02 遍历的范围
     -03 是否停止遍历
     
     */
    
    //遍历副文本
    var resultStr = ""
    
    // 遍历富文本
    composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (dict, range, _) -> Void in
        
        // 如果是文本附件
        if let att = dict["NSAttachment"] as? YRTextAttachment {
            resultStr += (att.emotion?.chs ?? "")
        }else {
            // 文字
            let name = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
            resultStr += name
        }
    }
    
    // 如果配图中的数组.count > 0 代表发送有图片微博
    if pictureView.imageList.count > 0{
        upload(resultStr)
    }else{
        // 发送文字微博
        update(resultStr)
    }
}
    
   //MARK: - 懒加载控件
    
    private lazy var navLabel : UILabel = {
        
        let name = YRUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        let str = "发布微博\n\(name)"
        let range = (str as NSString).rangeOfString(name)
        let attributed = NSMutableAttributedString(string: str)
        attributed.addAttributes([NSForegroundColorAttributeName : ThemeColor,NSFontAttributeName : UIFont.systemFontOfSize(14)], range: range)
        let label = UILabel()
        label.attributedText = attributed
        label.textAlignment = .Center
        label.numberOfLines = 0
        label.sizeToFit()
        
        return label
    }()
    private lazy var composeTextView : YRComposeTextView = {
        
        let view = YRComposeTextView()
        //允许textView拖动
        view.alwaysBounceVertical = true
        view.placeholder = "请在这里输入您要发送的微博文字请在这里输入您要发送的微博文字请在这里输入您要发送的微博文字请在这里输入您要发送的微博文字"
        view.font = UIFont.systemFontOfSize(17)
        
        view.delegate = self
        return view
    }()
    
    //底部toolBar
    private lazy var composeToolBar : YRComposeToolBar = YRComposeToolBar()
    //配图
    private lazy var pictureView : YRComposePictureView = YRComposePictureView()
    //表情键盘
    private lazy var emotionView : YREmotionKeyBoard = {
        
       let view = YREmotionKeyBoard()
        view.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        return view
        
    }()
}
//处理tabBar按钮点击
extension YRComposeController{
    //选择图片
    func selectImage(){
        
        let pick = UIImagePickerController()
        //设置代理
        pick.delegate = self
        presentViewController(pick, animated: true, completion: nil)
        
    }
    //切换键盘
    func switchKeyboard(){
        
        /*
         
         判断当前显示的是系统键盘还是自定义表情键盘
         
         */
        //系统键盘
        if composeTextView.inputView == nil {
            
             composeTextView.inputView = emotionView
            
            composeToolBar.isEmotion = true
            
        }else{
            //自定义表情键盘
            composeTextView.inputView = nil
            
            composeToolBar.isEmotion = false
            
        }
        //刷新InputView
        composeTextView.reloadInputViews()
        //成为第一响应者
        composeTextView.becomeFirstResponder()
        
    }

}

extension YRComposeController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    
        
        //压缩图片方式01
//        let data = UIImagePNGRepresentation(svaleImageOfWidth(600, image: image))
//        data?.writeToFile("/Users/Viper/Desktop/嘎嘎", atomically: true)
        
        //压缩图片方式02 参数2->压缩系数0~1之间
//        let data1 = UIImageJPEGRepresentation(image, 0.2)
//        data1?.writeToFile("/Users/Viper/Desktop/嘎嘎", atomically: true)

//        print(image)
        //填充图片
        // 填充图片
        pictureView.addImages(svaleImageOfWidth(600, image: image))
        // 如果实现代理方法 系统将不再帮程序员关闭控制器
        picker.dismissViewControllerAnimated(false, completion: nil)    }
    
    /*
     1200 压缩后的结果->600
     600  ----------->300
     如果传入的图片宽度为500 那么原图返回
     */
    
//    //压缩图片
    func svaleImageOfWidth(width : CGFloat,image : UIImage)->UIImage{
        
        //如果传入的图片宽度小于我们指定压缩的宽度的话 直接返回 
        if width > image.size.width {
            
            return image
        }
        //等比例计算出图片的高度
        let height = (width * image.size.height)/image.size.width
        
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        /*
         
         上下文
         -开启上下文
         -将图片渲染到上下文中
         -获取上下文的结果
         -关闭上下文
         */
        
        UIGraphicsBeginImageContext(rect.size)
        image.drawInRect(rect)
        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return result
   
    }
}

//发送文字微博请求
extension YRComposeController{
    
    func update(stauts : String){
        //发送文字微博
        YRNetwoekTools.sharedTools.composeUpdate(stauts, success: { (response) in
             print("成功")
            }) { (error) in
                 print("失败\(error)")
        }
    }
    
    //发送图片微博请求
    func upload(stauts : String){
        
                    YRNetwoekTools.sharedTools.comoposeUpload(stauts, imageList: pictureView.imageList, success: { (response) -> () in
                print("发送成功")
            }) { (error) -> () in
                print("发送失败")
        }
    }
}
extension YRComposeController : UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        //监听是否有文字 没有文字时发送按钮禁用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //拖动textView隐藏键盘
        composeTextView.resignFirstResponder()

    }
    
}
